﻿using System;
using System.Net;
using System.Net.Mail;
using ChampionsLeagueBets.Domain;

namespace ChampionsLeagueBets.Web.Mvc.Common
{
	public static class EmailManager
	{
		public static Email SendEmail(Email email)
		{
			using (SmtpClient smtpClient = new SmtpClient())
			{
				// Adres serwera pocztowego
				smtpClient.Host = SettingManagementService.SmtpServer;
				// Portserwera pocztowego
				smtpClient.Port = SettingManagementService.SmtpPort;

				//Autoryzacja
				if (!string.IsNullOrWhiteSpace(SettingManagementService.SmtpLogin) && !string.IsNullOrWhiteSpace(SettingManagementService.SmtpPassword))
					smtpClient.Credentials = new NetworkCredential(SettingManagementService.SmtpLogin, SettingManagementService.SmtpPassword);

				using (MailMessage message = new MailMessage())
				{
					message.IsBodyHtml = true;
					message.From = new MailAddress(SettingManagementService.SmtpSenderAddress, SettingManagementService.SmtpSenderName);
					message.To.Add(new MailAddress(email.ReceiverAddress, email.ReceiverName));
					message.Body = email.Body;
					message.Subject = email.Subject;

					//foreach (EmailAttachment att in email.Attachments)
					//{
					//    message.Attachments.Add(new Attachment(att.FilePath, att.MimeType));
					//}

					try
					{
						email.LastTrySendDate = DateTime.Now;
						email.Count++;
						smtpClient.Send(message);
						email.IsSend = true;
						email.SendDate = DateTime.Now;
					}
					catch (Exception exception)
					{
						email.IsSend = false;
						email.Error = exception.ToString();
						//Logger.Instance.Error("TaskEmailSender thread", exception);
					}
				}
			}

			return email;
		}
	}
}